package cn.demomaster.quickpermission;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.demomaster.quickpermission.listener.PermissionResultCallback;

public class PermissionRequest {
    static final String TAG = "PermissionRequest";
    int requestCode;
    int requestIndex =0;//权限请求索引
    //IPermissionHandler permissionHandler;
    //List<PermissionModel> permissionModelList;
    List<String> permissions;
    PermissionResultCallback callback;

    public PermissionRequest() {
        requestCode = (int) (System.currentTimeMillis() % 10000);
        //baseCode = (int) (System.currentTimeMillis() % 10000);
    }

    public int getRequestCode() {
        return requestCode;
    }

    public int getRequestIndex() {
        return requestIndex;
    }
    //    public void setIndex(int index) {
//        this.index = index;
//    }

//    public List<PermissionModel> getPermissionModelList() {
//        return permissionModelList;
//    }
//
//    public void setPermissionModelList(List<PermissionModel> permissionModelList) {
//        this.permissionModelList = permissionModelList;
//    }

    public void setRequestCode(int requestCode) {
        this.requestCode = requestCode;
    }

    public PermissionRequest callback(PermissionResultCallback callback) {
        this.callback = callback;
        return this;
    }

    public PermissionRequest permissions(List<String> permissions) {
        return permissions(permissions.toArray(new String[permissions.size()]));
    }
    public PermissionRequest permissions(String... permissions) {
        Map<String,String> permissionMap = new HashMap<>();
        for(String permission:permissions){
            permissionMap.put(permission, permission);
        }
        this.permissions = new ArrayList<>();
        for (Map.Entry<String, String> entry : permissionMap.entrySet()) {
            this.permissions.add(entry.getKey());
        }
        return this;
    }

    public void request() {
        QuickPermission2.getInstance().requestPermission( this);
    }

    public String getCurrentPermission() {
        if(permissions==null){
            return null;
        }
        if(requestIndex>=permissions.size()){
            return null;
        }
       return permissions.get(requestIndex);
    }

    public void granted() {
        if (callback != null) {
            callback.onPermissionsGranted(permissions.toArray(new String[permissions.size()]));
        }
    }

    public void denied() {
        if (callback != null) {
            callback.onPermissionsDenied();
        }
    }

    public void cancel() {
        Log.e(TAG, "cancel: ");
        if(QuickPermission2.getInstance().checkPermission(permissions)){
            granted();
        }else {
            denied();
        }
    }

    public void next() {
        requestIndex+=1;
    }
}
